package com.pay.dubbo.wx;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.pay.constants.WeixinConstants;
import com.pay.util.HttpClientUtil;

/**
 * @Description: 微信交互服务
 * @see: WxServiceFacadeImpl 此处填写需要参考的类
 * @version 2016年9月20日 上午9:23:28
 * @author shulin.feng
 */
@Service("wxServiceFacade")
@PropertySource("classpath:/application.properties")
public class WxServiceFacadeImpl implements WxServiceFacade {
	private Logger logger = LoggerFactory.getLogger(WxServiceFacadeImpl.class);
	@Value("${gate.proxy.address}")
    private static String proxyAddress = null;
	@Value("${gate.proxy.port}")
    private static int proxyPort = 3128;
	/**
	 * 网页授权获取accessToken
	 */
	@Override
	public String getOauth2AccessToken(String appid, String appsecret, String code) {
		logger.info("geta服务getOauth2AccessToken请求参数 appid:{},appsecret:{},code:{}", appid, appsecret, code);
		StringBuilder sb = new StringBuilder();
		sb.append("appid=").append(appid).append("&secret=").append(appsecret).append("&code=").append(code)
				.append("&grant_type=").append("authorization_code");
		String content = HttpClientUtil.sendGet(WeixinConstants.oauth2AccessTokenUrl, sb.toString(),true,proxyAddress,proxyPort);
		logger.info("geta服务wxServiceFacade 返回结果:{}", content);
		return content;
	}
	
	/**
	 * 网页授权获取用户信息
	 */
	@Override
	public String getOauth2UserInfo(String accessToken, String openId) {
		logger.info("geta服务getOauth2UserInfo请求参数 accessToken:{},openId:{}", accessToken, openId);
		StringBuilder sb = new StringBuilder();
		sb.append("access_token=");
		sb.append(accessToken);
		sb.append("&openid=");
		sb.append(openId);
		sb.append("&lang=zh_CN");
		String content = HttpClientUtil.sendGet(WeixinConstants.userInfoUrl, sb.toString(),true,proxyAddress,proxyPort);
		logger.info("geta服务getOauth2UserInfo 返回结果:{}", content);
		return content;
	}

	/**
	 * 发送模板/客服消息
	 */
	@Override
	public String sendMessage(String wxUrl, String accessToken, String content) {
		logger.info("geta服务sendMessage请求参数 wxUrl:{},accessToken:{},content:{}", wxUrl, accessToken, content);
		StringBuilder sb = new StringBuilder(wxUrl);
		sb.append(accessToken);
		String result = HttpClientUtil.sendPost(sb.toString(), content,true,proxyAddress,proxyPort);
		logger.info("geta服务sendMessage 返回结果:{}", result);
		return result;
	}

	/**
	 * 获取accessToken
	 */
	@Override
	public String getAccessToken(String lfappid, String lfappsecret) {
		logger.info("geta服务getAccessToken请求参数 appid:{},appsecret:{}", lfappid, lfappsecret);
		StringBuilder sb = new StringBuilder();
		sb.append("grant_type=").append("client_credential").append("&appid=").append(lfappid).append("&secret=")
				.append(lfappsecret);
		String content = HttpClientUtil.sendGet(WeixinConstants.tokenUrl, sb.toString(),true,proxyAddress,proxyPort);
		logger.info("geta服务getAccessToken 返回结果:{}", content);
		return content;
	}

	/**
	 * 获取未接入会话列表
	 */
	@Override
	public String getWaitCase(String accessToken) {
		logger.info("geta服务getWaitCase请求参数 accessToken:{}", accessToken);
		StringBuilder sb = new StringBuilder();
		sb.append("access_token=");
		sb.append(accessToken);
		String content = HttpClientUtil.sendGet(WeixinConstants.kfsessionGetwaitCaseUrl, sb.toString(),true,proxyAddress,proxyPort);
		logger.info("geta服务getWaitCase 返回结果:{}", content);
		return content;
	}

	/**
	 * 获取api_ticket
	 */
	@Override
	public String getApiTicket(String accessToken) {
		logger.info("geta服务getApiTicket请求参数 accessToken:{}", accessToken);
		StringBuilder sb = new StringBuilder();
		sb.append("access_token=");
		sb.append(accessToken);
		sb.append("&type=");
		sb.append("jsapi");
		String content = HttpClientUtil.sendGet(WeixinConstants.jsApiTicketUrl, sb.toString(),true,proxyAddress,proxyPort);
		logger.info("geta服务getApiTicket 返回结果:{}", content);
		return content;
	}

	/**
	 * 创建会话
	 */
	@Override
	public String createKfsession(String accessToken, String params) {
		logger.info("geta服务createKfsession请求参数 accessToken:{},params:{}", accessToken, params);
		StringBuilder sb = new StringBuilder(WeixinConstants.kfsessionCreateUrl);
		sb.append(accessToken);
		String content = HttpClientUtil.sendPost(sb.toString(), params,true,proxyAddress,proxyPort);
		logger.info("geta服务createKfsession 返回结果:{}", content);
		return content;
	}

	/**
	 * 获取客户的会话状态
	 */
	@Override
	public String getKfSession(String accessToken, String openId) {
		logger.info("geta服务getKfSession请求参数 accessToken:{},openId:{}", accessToken, openId);
		StringBuilder sb = new StringBuilder();
		sb.append("access_token=");
		sb.append(accessToken);
		sb.append("&openid=");
		sb.append(openId);
		String content = HttpClientUtil.sendGet(WeixinConstants.kfsessionGetsessionUrl, sb.toString(),true,proxyAddress,proxyPort);
		logger.info("geta服务getKfSession 返回结果:{}", content);
		return content;
	}

	@Override
	public String getMsgRecord(String accessToken, String starttime, String endtime, int pagesize, int pageindex) {
		logger.info("geta服务getMsgRecord请求参数 accessToken:{},starttime:{},endtime:{},pagesize:{},pageindex:{}",
				accessToken, starttime, endtime, pagesize, pageindex);
		StringBuilder sb = new StringBuilder(WeixinConstants.kfmsgRecordUrl);
		sb.append(accessToken);
		Map<String, String> map = new HashMap<>();
		map.put("starttime", starttime);
		map.put("endtime", endtime);
		map.put("pageindex", String.valueOf(pageindex));
		map.put("pagesize", String.valueOf(pagesize));
		String content = HttpClientUtil.sendPost(sb.toString(), JSON.toJSONString(map),true,proxyAddress,proxyPort);
		logger.info("geta服务getMsgRecord 返回结果:{}", content);
		return content;
	}

	/**
	 * 获取在线客服接待信息
	 */
	@Override
	public String getKfOnlineList(String accessToken) {
		logger.info("geta服务getKfOnlineList请求参数 accessToken:{}", accessToken);
		StringBuilder sb = new StringBuilder();
		sb.append("access_token=");
		sb.append(accessToken);
		String content = HttpClientUtil.sendGet(WeixinConstants.kfOnlineListUrl, sb.toString(),true,proxyAddress,proxyPort);
		logger.info("geta服务getKfOnlineList 返回结果:{}", content);
		return content;
	}

	@Override
	public String getUserInfo(String accessToken, String openId) {
		logger.info("geta服务getUserInfo请求参数 accessToken:{},openId:{}", accessToken, openId);
		StringBuilder sb = new StringBuilder();
		sb.append("access_token=");
		sb.append(accessToken);
		sb.append("&openid=");
		sb.append(openId);
		sb.append("&lang=zh_CN");
		String content = HttpClientUtil.sendGet(WeixinConstants.cgiuserInfoUrl, sb.toString(),true,proxyAddress,proxyPort);
		logger.info("geta服务getUserInfo 返回结果:{}", content);
		return content;
	}


	/**
	 * @Description 获取公众号永久二维码
	 * @param accessToken
	 * @param content
	 * @return
	 * @see 需要参考的类或方法
	 */
	@Override
	public String createQrcode(String accessToken, String content) {
		logger.info("geta服务createQrcode请求参数 accessToken:{},sence:{}", accessToken, content);
		StringBuilder sb = new StringBuilder(WeixinConstants.qrcodeUrl);
		sb.append(accessToken);
		String result = HttpClientUtil.sendPost(sb.toString(), content,true,proxyAddress,proxyPort);
		logger.info("geta服务createQrcode 返回结果:{}", result);
		return result;
	}

	/**
	 * @Description 获取微信用户列表
	 * @param accessToken
	 * @param nextOpenId
	 * @return
	 * @see 需要参考的类或方法
	 */
	@Override
	public String getUserInfoList(String accessToken, String nextOpenId) {
		logger.info("geta服务getUserInfoList请求参数 accessToken:{},nextOpenId:{}", accessToken, nextOpenId);
		StringBuilder sb = new StringBuilder();
		sb.append("access_token=").append(accessToken).append("&next_openid=").append(nextOpenId);
		String content = HttpClientUtil.sendGet(WeixinConstants.userListInfoUrl, sb.toString(),true,proxyAddress,proxyPort);
		return content;
	}

	/**
	 * 上传微信图片素材
	 */
	@Override
	public String uploadimg(byte[] file, String accessToken, String name) {
		try {
			URL urlObj = new URL("https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=" + accessToken);
			HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
			String result = null;
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false); // post方式不能使用缓存
			// 设置请求头信息
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			// 设置边界
			String BOUNDARY = "----------" + System.currentTimeMillis();
			con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
			// 请求正文信息
			// 第一部分：
			StringBuilder sb = new StringBuilder();
			sb.append("--"); // 必须多两道线
			sb.append(BOUNDARY);
			sb.append("\r\n");
			sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + name + "\"\r\n");
			sb.append("Content-Type:application/octet-stream\r\n\r\n");
			byte[] head = sb.toString().getBytes("utf-8");
			// 获得输出流
			OutputStream out = new DataOutputStream(con.getOutputStream());
			// 输出表头
			out.write(head);
			// 文件正文部分
			// 把文件已流文件的方式 推入到url中
			DataInputStream in = new DataInputStream(new ByteArrayInputStream(file));
			int bytes = 0;
			byte[] bufferOut = new byte[1024];
			while ((bytes = in.read(bufferOut)) != -1) {
				out.write(bufferOut, 0, bytes);
			}
			in.close();
			// 结尾部分
			byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
			out.write(foot);
			out.flush();
			out.close();
			StringBuffer buffer = new StringBuffer();
			BufferedReader reader = null;
			try {
				// 定义BufferedReader输入流来读取URL的响应
				reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
				String line = null;
				while ((line = reader.readLine()) != null) {
					buffer.append(line);
				}
				if (result == null) {
					result = buffer.toString();
				}
			} catch (IOException e) {
				System.out.println("发送POST请求出现异常！" + e);
				e.printStackTrace();
				throw new IOException("数据读取异常");
			} finally {
				if (reader != null) {
					reader.close();
				}
			}
			return result;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

}
